import 'package:bai_le_men_im/cmomon/userModel.dart';
import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/components/updateApp.dart';
import 'package:bai_le_men_im/conversation/messagesPage.dart' as prefix0;
import 'package:bai_le_men_im/home/conversationList.dart';
import 'package:bai_le_men_im/pages/search/all.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../pages/addFriends.dart';

import '../constants.dart' show Constants, AppColors, AppStyles;
import '../i18n/strings.dart' show Strings;

import '../modal/conversation.dart'
    show Conversation, Device, ConversationPageData;

import './conversation_page.dart';
import './contacts_page.dart';
import './discover_page.dart';
import './functions_page.dart';

import '../cmomon/conversationList.dart';
import '../cmomon/usersModel.dart';
import 'package:provider/provider.dart';
import '../cmomon/global.dart' as GloabalData;
import '../models/index.dart';
import 'package:intl/intl.dart';

import 'package:overlay_support/overlay_support.dart';

enum ActionItems { GROUP_CHAT, ADD_FRIEND, QR_SCAN, PAYMENT, HELP }

final DateFormat formatter = new DateFormat('HH:mm');

class NavigationIconView {
  final BottomNavigationBarItem item;

  NavigationIconView(
      {Key key, String title, IconData icon, IconData activeIcon})
      : item = BottomNavigationBarItem(
          icon: Icon(icon),
          activeIcon: Icon(activeIcon),
          title: Text(title),
          backgroundColor: Colors.white,
        );
}

class HomeScreen extends StatefulWidget {
  String title = Strings.TitleWechat;
  Color headerColor;

  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  static const HeaderColor = const Color(AppColors.PrimaryColor);
  PageController _pageController;
  int _currentIndex = 0;
  List<NavigationIconView> _navigationViews;
  List<Widget> _pages;
  List<Widget> _mainActions;
  List<Widget> _functionActions;
  bool isInitialized = false;
  bool isHotReload = false;

  ConversationModel conversationModel;

  bool _isAvatarFromNet(avatar) {
    return avatar.startsWith('http') || avatar.startsWith('https');
  }

  @override
  void reassemble() {
    // TODO: implement reassemble

    super.reassemble();
    isHotReload = true;
    print('home screen reassemble');
  }

  @override
  void didUpdateWidget(HomeScreen oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    print('home screen didUpdateWidget');
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   if (isHotReload) {
  //     isHotReload = false;
  //     getConversationList();
  //   }
  //   print('homescreen didChangeDependencies');
  //   if (isInitialized) return;
  //   print('重新绑定');
  //   isInitialized = true;
  //   print('homescreen run getConversationList');

  //   conversationModel = Provider.of<ConversationModel>(context);
  //   FlutterWildfire.on("receiveMessage", receiveMessageHandler);
  //   getConversationList();
  // }

  getConversationList() async {
    var result =
        await FlutterWildfire.getConversationList(['Single', 'Group'], [0]);
    conversationModel.list =
        List.generate(result.length, (int index) => result[index]);
    return;
    print('循环开始');
    var conversations = List.generate(result.length, (int index) {
      var item = result[index];
      DateTime time =
          new DateTime.fromMillisecondsSinceEpoch(item['timestamp']);
      String formatted = formatter.format(time);
      String otherSideUserId = item['conversation']['target'];
      String des;
      if (item['lastMessage']['content']['content'] != null) {
        des = item['lastMessage']['content']['content'];
      } else {
        switch (item['lastMessage']['content']['mediaType']) {
          case 'IMAGE':
            des = '[图片]';
            break;
          case 'VOICE':
            des = '[语音消息]';
            break;
          default:
            print('[未知类型]');
            print(item['lastMessage']);
            des = '[未知类型]';
        }
      }
      return Conversation(
        otherSideUserId: otherSideUserId,
        avatar: 'https://randomuser.me/api/portraits/men/10.jpg',
        title: otherSideUserId,
        // des: item['lastMessage']['content']['content'],
        des: des,
        updateAt: formatted,
        isMute: false,
        unreadMsgCount: item['unreadCount']['unread'],
      );
    });
    print('循环完毕');
    conversationModel.list = conversations;
    // data = ConversationPageData(conversations: conversations, device: null);
    // this.setState(() {});
    // return result;
  }

  receiveMessageHandler(dynamic messages) async {
    // print(Global.)
    print('home screen receiveMessageHandler');
    if (!GloabalData.Global.isReFetchWhenReseveMessage) {
      print('暂时阻止更新');
      return;
    }
    var message = messages[0];
    if (message['type'] != null && message['type'] == 'TypingMessageContent') {
      return;
    }
    String otherSideUserId = message['conversation']['target'];
    var subtreeContext = ModalRoute.of(context).subtreeContext;
    print('subtreeContext');
    print(subtreeContext);

    print('overlayEntries');
    List overlayEntries = ModalRoute.of(context).overlayEntries;
    print(overlayEntries);
    // if (ModalRoute.of(context).isCurrent) {
    //   return;
    // }
    getConversationList();
    if (GloabalData.Global.currentChatUserId != otherSideUserId) {
      String content;
      User targetUser;
      Group targetGroup;
      Widget avatar;
      if (message['type'] != null) {
        // TODO: 有可能是单条文本消息, 或者图片消息
        // recevieSigleMessage(message);
        switch (message['type']) {
          case 'TypingMessageContent':
            return;
            break;
          case 'TextMessageContent':
            content = message['content']['content'];
            break;
          case 'ImageMessageContent':
            switch (message['content']['mediaType']) {
              case 'IMAGE':
                content = '[图片]';
                break;
              default:
                print(message);
                print('未知媒体类型');
                content = '[未知媒体类型]';
            }
            break;
          case 'SoundMessageContent':
            content = '[语音消息]';
            break;
          case 'CreateGroupNotificationContent':
            print(message);
            content = '[群创建成功]';
            break;
          default:
            print('[未知消息类型]');
            print(message);
            content = '[未知消息类型]';
        }

        targetUser = await Provider.of<UsersModel>(context, listen: false)
            .getUserInfoById(otherSideUserId);
        avatar = myAvatar(targetUser.portrait);
      }
      if (content != null) {
        showOverlayNotification((context) {
          return Card(
            margin: const EdgeInsets.symmetric(horizontal: 4),
            child: SafeArea(
              child: ListTile(
                onTap: () {
                  OverlaySupportEntry.of(context).dismiss();
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (context) {
                    return prefix0.MessagesPage(user: targetUser);
                  }));
                },
                leading: SizedBox.fromSize(
                    size: const Size(40, 40), child: ClipOval(child: avatar)),
                title: Text(targetUser.displayName),
                subtitle: Text(content),
                trailing: IconButton(
                    icon: Icon(Icons.close),
                    onPressed: () {
                      OverlaySupportEntry.of(context).dismiss();
                    }),
              ),
            ),
          );
        }, duration: Duration(milliseconds: 2000));
      }
    }
    // getConversationList();
    return;
    // 回话列表：  [{conversation: {line: 0, target: 383d3djj, type: Single}, draft: , isSilent: false, isTop: false, lastMessage: {content: {content: ttgg, extra: hello extra, mentionedTargets: [], mentionedType: 0}, conversation: {line: 0, target: 383d3djj, type: Single}, direction: Receive, messageId: 19, messageUid: 111159129189416991, sender: 383d3djj, serverTime: 1567740803271, status: Unread}, timestamp: 1567740803271, unreadCount: {unread: 9, unreadMention: 0, unreadMentionAll: 0}}, {conversation: {line: 0, target: admin, type: Single}, draft: , isSilent: false, isTop: false, lastMessage: {content: {content: ��迎您的归来，如果使用过程中有什么疑问请���入 http://bbs.wildfirechat.cn 进行讨论。请关注微信公众号"野火IM"接收野火IM的最新资讯。, extra: , mentionedTargets: [], mentionedType: 0}, conversation: {line: 0, target: admin, type: Single}, direction: Receive, messageId: 18, messageUid: 111158845513957405, sender: admin, serverTime: 1567740668004, status: Unread}, timestamp:
    // connect 后收到的数据 ： [{type: TextMessageContent, content: {content: 欢迎您的归来，如果使用过程中有什么疑问请加入 http://bbs.wildfirechat.cn 进行讨论。请关��微信公众号"野火IM"接收野火IM的最新资讯。, extra: , mentionedTargets: [], mentionedType: 0}, conversation: {line: 0, target: admin, type: Single}, messageId: 18, messageUid: 111158845513957405, sender: admin, serverTime: 1567740668004, status: Unread}]
    // 正在输入的状态 ： [{type: TypingMessageContent, content: {typingType: 0, extra: , mentionedType: 0}, conversation: {line: 0, target: 383d3djj, type: Single}, messageId: 0, messageUid: 111159124902838302, sender: 383d3djj, serverTime: 1567740801227, status: Unread}]
    // 收到新的消息��� [{type: TextMessageContent, content: {content: ttgg, extra: hello extra, mentionedTargets: [], mentionedType: 0}, conversation: {line: 0, target: 383d3djj, type: Single}, messageId: 19, messageUid: 111159129189416991, sender: 383d3djj, serverTime: 1567740803271, status: Unread}]
    // 给对方发消息： [{type: TextMessageContent, content: {content: ttgg, extra: hello extra, mentionedTargets: [], mentionedType: 0}, conversation: {line: 0, target: 383d3djj, type: Single}, messageId: 19, messageUid: 111328924671181020, sender: 151j1jBB, serverTime: 1567821768066, status: Sent}]
  }

  recevieSigleMessage(message) {
    /*
    DateTime time =
        new DateTime.fromMillisecondsSinceEpoch(message['serverTime']);
    String formatted = formatter.format(time);
    String otherSideUserId = message['conversation']['target'];
    List conversations = conversationModel.list;
    print(formatted);
    int index = conversations.indexWhere((conversation) {
      print('conversation.otherSideUserId =' + conversation.otherSideUserId);
      return conversation.otherSideUserId == otherSideUserId;
    });
    //600 1000 1300
    String des;
    if (message['content']['content'] != null) {
      des = message['content']['content'];
    } else {
      switch (message['content']['mediaType']) {
        case 'IMAGE':
          des = '[图片]';
          break;
        default:
          print(message['lastMessage']);
          print('未知类型');
          des = '[未知类型]';
      }
    }
    if (index > -1) {
      int _oldUnreadMsgCount = conversations[index].unreadMsgCount;
      // TODO: 头像
      var _newRecord = Conversation(
        otherSideUserId: otherSideUserId,
        avatar: 'https://randomuser.me/api/portraits/men/10.jpg',
        title: otherSideUserId,
        des: des,
        updateAt: formatted,
        isMute: false,
        unreadMsgCount: _oldUnreadMsgCount + 1,
      );
      // conversations.replaceRange(index, index + 1, [_newRecord]);
      conversations.removeAt(index);
      conversations.insert(index, _newRecord);
    } else {
      // conversations
      print('没找到');

      var _newRecord = Conversation(
        otherSideUserId: otherSideUserId,
        avatar: 'https://randomuser.me/api/portraits/men/10.jpg',
        title: otherSideUserId,
        des: des,
        updateAt: formatted,
        isMute: false,
        unreadMsgCount: 1,
      );
      conversations.insert(0, _newRecord);
    }
    */
    // conversationModel.list = conversations;
    // data = ConversationPageData(conversations: conversations, device: null);
    // TODO: 收到别人的短信后的弹窗
    // this.setState(() {});
  }

  @override
  void dispose() {
    print('homescreen dispose');
    isInitialized = false;
    // FlutterWildfire.off("receiveMessage", receiveMessageHandler);
    FlutterWildfire.disconnect();
    super.dispose();
  }

  void initState() {
    super.initState();
    print('home_screen initState');
    widget.headerColor = HeaderColor;

    // 初始化前3个界面的操作按钮
    _mainActions = [
      IconButton(
        icon: Icon(
            IconData(
              0xe65e,
              fontFamily: Constants.IconFontFamily,
            ),
            size: Constants.ActionIconSize,
            color: const Color(AppColors.ActionIconColor)),
        onPressed: () {
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return SearchKeywordInAll();
          }));
        },
      ),
      Container(width: 16.0),
      Theme(
        data: ThemeData(cardColor: Color(AppColors.ActionMenuBgColor)),
        child: PopupMenuButton(
          itemBuilder: (BuildContext context) {
            return <PopupMenuItem<ActionItems>>[
              PopupMenuItem(
                child: _buildPopupMunuItem(0xe69e, Strings.MenuGroupChat),
                value: ActionItems.GROUP_CHAT,
              ),
              PopupMenuItem(
                child: _buildPopupMunuItem(0xe638, Strings.MenuAddFriends),
                value: ActionItems.ADD_FRIEND,
              ),
              PopupMenuItem(
                child: _buildPopupMunuItem(0xe61b, Strings.MenuQRScan),
                value: ActionItems.QR_SCAN,
              ),
              // PopupMenuItem(
              //   child: _buildPopupMunuItem(0xe62a, Strings.MenuPayments),
              //   value: ActionItems.PAYMENT,
              // ),
              // PopupMenuItem(
              //   child: _buildPopupMunuItem(0xe63d, Strings.MenuHelp),
              //   value: ActionItems.HELP,
              // ),
            ];
          },
          icon: Icon(
              IconData(
                0xe60e,
                fontFamily: Constants.IconFontFamily,
              ),
              size: Constants.ActionIconSize + 4.0,
              color: const Color(AppColors.ActionIconColor)),
          onSelected: (ActionItems selected) {
            switch (selected) {
              case ActionItems.ADD_FRIEND:
                Navigator.of(context)
                    .push(new MaterialPageRoute(builder: (context) {
                  return AddFriendPage();
                }));
                break;
              case ActionItems.QR_SCAN:
                pushPageToQrCodeScanner(context);
                break;
              default:
                print('点击的是$selected');
            }
          },
        ),
      ),
      Container(width: 16.0),
    ];
    _functionActions = [
      UpdateApp(showButton: false,),
      // IconButton(
      //   icon: Icon(
      //       IconData(
      //         0xe60a,
      //         fontFamily: Constants.IconFontFamily,
      //       ),
      //       size: Constants.ActionIconSize + 4.0,
      //       color: const Color(AppColors.ActionIconColor)),
      //   onPressed: () {
      //     print('打开相机拍短视频');
      //   },
      // ),
      Container(width: 16.0),
    ];

    _navigationViews = [
      NavigationIconView(
        title: Strings.TitleWechat,
        icon: IconData(
          0xe608,
          fontFamily: Constants.IconFontFamily,
        ),
        activeIcon: IconData(
          0xe603,
          fontFamily: Constants.IconFontFamily,
        ),
      ),
      NavigationIconView(
          title: Strings.TitleContact,
          icon: IconData(
            0xe601,
            fontFamily: Constants.IconFontFamily,
          ),
          activeIcon: IconData(
            0xe656,
            fontFamily: Constants.IconFontFamily,
          )),
      NavigationIconView(
          title: Strings.TitleDiscovery,
          icon: IconData(
            0xe600,
            fontFamily: Constants.IconFontFamily,
          ),
          activeIcon: IconData(
            0xe671,
            fontFamily: Constants.IconFontFamily,
          )),
      NavigationIconView(
          title: Strings.TitleMe,
          icon: IconData(
            0xe6c0,
            fontFamily: Constants.IconFontFamily,
          ),
          activeIcon: IconData(
            0xe626,
            fontFamily: Constants.IconFontFamily,
          )),
    ];
    _pageController = PageController(initialPage: _currentIndex);
    _pages = [
      ConversationListPage(),
      ContactsPage(),
      DiscoverPage(),
      FunctionsPage(),
    ];
  }

  _buildPopupMunuItem(int iconName, String title) {
    return Row(
      children: <Widget>[
        Icon(
            IconData(
              iconName,
              fontFamily: Constants.IconFontFamily,
            ),
            size: 22.0,
            color: const Color(AppColors.AppBarPopupMenuColor)),
        Container(width: 12.0),
        Text(title,
            style:
                TextStyle(color: const Color(AppColors.AppBarPopupMenuColor))),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
      statusBarColor: Colors.transparent,
    ));
    final BottomNavigationBar botNavBar = BottomNavigationBar(
      fixedColor: const Color(AppColors.TabIconActive),
      items: _navigationViews.map((NavigationIconView view) {
        return view.item;
      }).toList(),
      currentIndex: _currentIndex,
      type: BottomNavigationBarType.fixed,
      onTap: (int index) {
        setState(() {
          _currentIndex = index;
          _pageController.jumpToPage(_currentIndex);
        });
      },
    );

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title, style: AppStyles.TitleStyle),
        elevation: 0.0,
        brightness: Brightness.light,
        backgroundColor: widget.headerColor,
        actions: _currentIndex == 3 ? _functionActions : _mainActions,
      ),
      body: PageView.builder(
        itemBuilder: (BuildContext context, int index) {
          return _pages[index];
        },
        controller: _pageController,
        itemCount: _pages.length,
        onPageChanged: (int index) {
          setState(() {
            _currentIndex = index;
            switch (index) {
              case 0:
                widget.title = Strings.TitleWechat;
                widget.headerColor = HeaderColor;
                break;
              case 1:
                widget.title = Strings.TitleContact;
                widget.headerColor = HeaderColor;
                break;
              case 2:
                widget.title = Strings.TitleDiscovery;
                widget.headerColor = HeaderColor;
                break;
              case 3:
                widget.title = '';
                widget.headerColor = Colors.white;
                break;
            }
          });
        },
      ),
      bottomNavigationBar: botNavBar,
    );
  }
}
